const fs = require('fs'),
  path = '';

function log() {
  var msgs = [];
  for (var i = 0; i < arguments.length; i++) {
    msgs.push(arguments[i])
  }
  var msg = genMsg()
  var className = require('../../lib/getClass')(msg);
  if (className == 'String' || className == 'Number' || className == 'Boolean') {
    if (msgs.length > 0) {
      className = require('../../lib/getClass')(msgs[0]);
      if (className == 'String' || className == 'Number' || className == 'Boolean') {
        msgs[0] = msg + className + ':' + msgs[0];
      } else {
        msgs.splice(0, 0, msg)
      }
    } else {
      msgs.splice(0, 0, msg)
    }
  } else {
    msgs.splice(0, 0, msg)
  }
  require('../mng/logMng').add(msgs)
  if (!path) {
    msgs.forEach(msg => {
      console.log(msg)
    })
  } else {
    fs.appendFile(path, msgs.join('\r\n') + '\r\n', (err) => {
      if (err) {
        console.log(err)
        return
      }
    })
  }
}

function genMsg() {
  var stack = new Error().stack,
    start = -1;
  for (var i = 0; i < 3; i++) {
    start = stack.indexOf('\n', start + 1);
    if (start == -1) {
      return stack
    }
  }
  start = stack.indexOf('at', start + 1) + 3;
  var end = stack.indexOf('\n', start),
    fileLine;
  if (end == -1)
    fileLine = stack.substring(start);
  else
    fileLine = stack.substring(start, end);
  start = fileLine.lastIndexOf('(');
  end = fileLine.lastIndexOf(')');
  if (start != -1 && end != -1) {
    fileLine = fileLine.substring(start + 1, end)
  }
  var date = new Date();
  var sDate = '';
  if (date.getMonth() < 9)
    sDate += '0';
  sDate += (date.getMonth() + 1) + '-'
  if (date.getDate() < 10)
    sDate += '0';
  sDate += date.getDate() + ' '
  if (date.getHours() < 10)
    sDate += '0';
  sDate += date.getHours() + ':'
  if (date.getMinutes() < 10)
    sDate += '0';
  sDate += date.getMinutes() + ':'
  if (date.getSeconds() < 10)
    sDate += '0';
  sDate += date.getSeconds()
  return '[' + sDate + ']' + fileLine + ':'
}

module.exports = log
